/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */

package cgl.narada.aggregator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

import cgl.narada.protocol.DataReceived;
import cgl.narada.protocol.Handler;
import cgl.narada.transport.TransportException;
import cgl.narada.transport.TransportHandler;
import cgl.narada.transport.TransportHandlerImpl;

/** This is an example which demonstrates using the transport interfaces in
    Narada. This class has presently been written for TCP communications.
    Subsequent versions of this class would include support for other
    transport types supported in NaradaBrokering.

    @author Shrideep Pallickara
    $Date$
    $Revision$
*/

public class NotifierNode implements Handler, InterchangeConstants {
  String moduleName = "NotifierNode: ";

  String aggregatorLink= null;

  /** Deals with the transport related aspects of communication */
  private TransportHandler transportHandler;

  /** The constructor for the notifier node has information pertaining to the
      Aggregation node passed to it. This includes the hostname, portnum and
      transport type information. */
  public NotifierNode(Properties commProps, String commType) {
    transportHandler = new TransportHandlerImpl(this);
    loadCommunicationsOfType(commProps, commType);
     /** currently we include info pertaining to factory and link creation in
	 one properties object. This is NOT the right model. */
    aggregatorLink = createLinkTo(commProps, commType);
    if (aggregatorLink == null) {
      System.out.println(moduleName + "Unable to create link to aggregator" +
			 "Check specified <hostname> <portnum> & <transport>");
    }
  }

  public void loadCommunicationsOfType(Properties commProps, String commType) {
    try {
      transportHandler.loadCommunicationsOfType(commProps, commType);
    } catch (TransportException transEx) {
      System.out.println(transEx);
    }
  }

  public String createLinkTo(Properties props, String linkType) {
    try {
      return transportHandler.setupLink(props, linkType);
    } catch (TransportException transEx) {
      System.out.println(transEx);
    }
    return null;
  }

  public void sendRegistrationToAggregator() {
    byte[] register = new byte[1]; /** one can add more info for registration
				       purposes */
    register[0] = REGISTER_NOTIFIER;
    sendDataTo(register, aggregatorLink);
  }

  public void sendDeregistrationToAggregator() {
    byte[] deregister = new byte[1];
    deregister[0] = DEREGISTER_NOTIFIER;
    sendDataTo(deregister, aggregatorLink);
  }


  public void sendDataTo(byte[] data, String node) {
    try {
      transportHandler.sendData(data, aggregatorLink);
    } catch (TransportException transEx) {
      System.out.println(transEx);
    }
  }

  /** This method indicates that the node in question is a client */
  public boolean isClient() {
    return true;
  }

  public void postInfoToAggregator() {
    String post = "This is my independent post to the aggregator";
    byte[] infoPost = new byte[1 + post.length()];
    int offset=0;
    infoPost[offset++] =  INFO_POST_FROM_NOTIFIER;
    System.arraycopy(post.getBytes(), 0,
                     infoPost, offset, post.length());
    sendDataTo(infoPost, aggregatorLink);
  }
  public void postInfoToAggregator(String s) {
  //    String post = "This is my independent post to the aggregator";
    String post = s;
    if (s!=null){
      byte[] infoPost = new byte[1 + post.length()];
      int offset=0;
      infoPost[offset++] =  INFO_POST_FROM_NOTIFIER;
      System.arraycopy(post.getBytes(), 0,
                       infoPost, offset, post.length());
      sendDataTo(infoPost, aggregatorLink);
    }
  }

  private void infoResponseToAggregator() {
    String response = "This is my response to your query";
    byte[] infoResponse = new byte[1 + response.length()];
    int offset=0;
    infoResponse[offset++] =  INFO_RESPONSE_FROM_NOTIFIER;
    System.arraycopy(response.getBytes(), 0,
		     infoResponse, offset, response.length());
    sendDataTo(infoResponse, aggregatorLink);
  }

  public void handleData(byte[] data, String sender) {

    if (data.length == 0) {
      System.out.println(moduleName + "Data received from " +
      		sender + " has length = 0");
      return;
    }

    int _dataInfo = (int) data[0];

    switch(_dataInfo) {
    case (int) INFO_REQUEST_FROM_AGGREGATOR:
      System.out.println(moduleName + "Received Info request from aggregator");
      infoResponseToAggregator();
      break;

    default:
      System.out.println(" Data[0] ->" + _dataInfo +
			 " Data length = " + data.length);
      break;
    }


  }


  public static void main(String[] args) {
    if (args.length != 2) {
      System.out.println("Usage: java cgl.narada.aggregator.NotifierNode " +
			 "<aggregator-host> <aggregator-port>");
      System.exit(0);
    }

    Properties props = new Properties();
    props.put("TCPServerPort", "0"); /** This ensures this node doesn't accept
					 connections from other nodes */
    props.put("hostname", args[0]);
    props.put("portnum", args[1]);
    NotifierNode notifier = new NotifierNode(props, "tcp");


    BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
    
    String cmd;
    System.out.println("\n Type h for help and usage indicators ... ");
    while (true) {
      try {
	cmd = r.readLine();
	if (cmd == null) {
	  break;
	}

	if(cmd.startsWith("h")) {
	  System.out.println("Register notifier                -> r ");
	  System.out.println("Deregister notifier              -> dr" );
	  System.out.println("Post Info to aggregator          -> p" );
	}

	if (cmd.startsWith("r")) {
	  notifier.sendRegistrationToAggregator();
	  continue;
	} /** end registration */

	if (cmd.startsWith("dr")) {
	  notifier.sendDeregistrationToAggregator();
	  continue;
	} /* end deregistration */

	if (cmd.startsWith("p")) {
	  notifier.postInfoToAggregator();
	}


      }catch (IOException ioe) {
	ioe.printStackTrace();
      } /* end try-catch */
    } /* end while(true) */

    System.out.println("NotifierNode shutting down services ....");
  }/*end main() */

}

